package net.erl.objects.pattern.impl;

import net.erl.objects.pattern.ErlPattern;
import net.erl.objects.pattern.EP;
import net.erl.objects.ErlTerm;

import java.util.HashMap;
import java.util.Map;

/**
 * I set a single variable to a term, or fail.
 */
public class ErlVarPattern extends ErlPatternBase {

    private String var;
    private ErlPattern match;

    public ErlVarPattern(String var) {
        this(var, EP.pany());
    }

    public ErlVarPattern(String var, ErlPattern match) {
        if (var == null || var.length() == 0) {
            throw new IllegalArgumentException("empty or null var in pattern");
        }
        if (match == null) {
            throw new IllegalArgumentException("null var matcher in pattern");
        }
        this.var = var;
        this.match = match;
    }

    public Map<String, ErlTerm> matchAndSet(ErlTerm term, Map<String, ErlTerm> vars) {
        if (term == null) {
            throw new IllegalArgumentException("null matched term");
        }

        vars = match.matchAndSet(term, vars);
        if (vars == null) {
            return null;
        }
        else {
            Map<String, ErlTerm> ret;

            if (vars.get(var) == null) {
                ret = new HashMap<String, ErlTerm>(vars);
                ret.put(var, term);
            } else {
                return null;
            }

            return ret;
        }
    }

}